package com.lsy.weizhi2.mybase;

import android.app.Application;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import com.baidu.mapapi.SDKInitializer;
import com.lsy.weizhi2.JsonObject.SelectLevel;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.CostomFlag;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.mysql.MySQLOperate;
import com.lsy.weizhi2.third.LocationService;
import com.lsy.weizhi2.utils.TextHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Created by 嗨哟 on 2017/3/13.
 */
public class BaseApp extends Application implements Thread.UncaughtExceptionHandler{
    private WindowManager mWindowManager;
    public static int SCREEN_WIDTH;
    public static int SCREEN_HEIGHT;
    public static int REAL_HEIGHT;
    public static Context context;
    public static LocationService locationService;
    public Vibrator mVibrator;
    private static Handler handler;
    public static File file1;

    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GeTuiActivity.geTuiAdapter == null)
     */
    public static LinkedList<String> linkedList=new LinkedList<>();
    public static String GeTui_ClientId;//个推id
    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(this);
        /**
         * 这个方法表示使用设计高度及 SCREEN_HEIGHT
         */
        //AutoLayoutConifg.getInstance().useDeviceSize();
        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        mWindowManager.getDefaultDisplay().getMetrics(metrics);
        SCREEN_WIDTH = metrics.widthPixels;//屏幕宽度（像素）
        SCREEN_HEIGHT = metrics.heightPixels;//屏幕高度(像素)
        REAL_HEIGHT = getHasVirtualKey();
        Log.i("height","SCREEN_HEIGHT==="+SCREEN_HEIGHT+"\n"+"REAL_HEIGHT=="+REAL_HEIGHT);
        /**
         * 获取状态栏高度——方法2
         * */
        int statusBarHeight2 = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            MyHeight.ACTIONBAR = getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        MyHeight.BannerHeight = 420*REAL_HEIGHT/1334+MyHeight.ACTIONBAR;
                Log.i("height","MyHeight.ACTIONBAR==="+MyHeight.ACTIONBAR);
        MyHeight.MyTitleHeight = 116*REAL_HEIGHT/1334;
        context = getApplicationContext();
        //电脑测试不开，手机效果要开，地图
        SDKInitializer.initialize(context);

        /***
         * 初始化定位sdk，建议在Application中创建
         */
        locationService = new LocationService(context);
        mVibrator =(Vibrator)context.getSystemService(Service.VIBRATOR_SERVICE);
        CostomFlag.list_select=new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                TextHelper.AnalyzeCity(context);
                //此处需要判断是否已存在
                CostomFlag.list_select=MySQLOperate.getInstance(context).Select_HomeGrid();
                if(CostomFlag.list_select==null||CostomFlag.list_select.size()==0){
                    for (int i = 0; i < 9; i++) {
                        SelectLevel level=new SelectLevel();
                        level.setImage(Constants.images[i]);
                        level.setName(Constants.names[i]);
                        level.setFid(Constants.first[i]);
                        level.setId(Constants.second[i]);
                        ContentValues values=new ContentValues();
                        values.put("first",Constants.first[i]);
                        values.put("second",Constants.second[i]);
                        values.put("name",Constants.names[i]);
                        values.put("place",Constants.images[i]);
                        values.put("id",i+1);
                        MySQLOperate.getInstance(context).Insert("homegrid",values,i+1);
                        CostomFlag.list_select.add(level);
                    }
                }
            }
        }).start();
        /**
         * 初始化主线程的handler---以便于个推SDK传递信息
         */
        if (handler == null) {
            handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case 0:
                            linkedList.add(0, (String) msg.obj);
                            break;

                        case 1:
                            if (GeTui_ClientId == null) {
                                GeTui_ClientId = (String) msg.obj;
                            }
                            break;
                    }
                }
            };
        }
        String path = Environment.getExternalStorageDirectory() + File.separator + "paizhao/";
        Log.i("BaseApp", "path====" + path);
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        file1=new File(file,"image1.jpg");
    }

    public int getHasVirtualKey() {
        int dpi = 0;
        Display display = mWindowManager.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            dpi = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }

    // 用来存储设备信息和异常信息
    private Map<String, String> info = new HashMap<String, String>();
    // 用于格式化日期,作为日志文件名的一部分
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        // 收集设备参数信息
        collectDeviceInfo(context);
        // 保存日志文件
        String text=saveCrashInfo2File(throwable);
        Log.i("BaseApp","返回信息=="+text);
        if(text!=null){
            System.exit(0);
            System.gc();
        }
    }

    public void collectDeviceInfo(Context context) {
        try {
            PackageManager pm = context.getPackageManager();// 获得包管理器
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);// 得到该应用的信息，即主Activity

            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                info.put("versionName", versionName);
                info.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Field[] fields = Build.class.getDeclaredFields();// 反射机制
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                info.put(field.getName(), field.get("").toString());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将异常信息保存至SD卡crash目录
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : info.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\r\n");
        }
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        ex.printStackTrace(pw);
        Throwable cause = ex.getCause();
        // 循环着把所有的异常信息写入writer中
        while (cause != null) {
            cause.printStackTrace(pw);
            cause = cause.getCause();
        }
        pw.close();// 记得关闭
        String result = writer.toString();
        sb.append(result);
        // 保存文件
        long timetamp = System.currentTimeMillis();
        String time = format.format(new Date());
        String fileName = "wzcrash-" + time + "_" + timetamp + ".log";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                File dir = new File(Environment.getExternalStorageDirectory(), "wzcrash");
                if (!dir.exists())
                    dir.mkdir();

                File file = new File(dir, fileName);
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(sb.toString().getBytes());
                fos.close();
                return fileName;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 个推sdk调用发送信息用
     * @param msg
     */
    public static void sendMessage(Message msg) {
        handler.sendMessage(msg);
    }
}
